<template>
  <div class="goods-management-container">
    <!-- 页面头部 -->
    <Header title="商品管理" class="page-header"></Header>

    <!-- 操作和搜索区域 -->
    <div class="action-section">
      <div class="filter-container">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索商品名称..."
          class="search-input"
          clearable
          :prefix-icon="Search"
          @input="searchGoods"
        />
        
        <el-select
          v-model="selectedCategory"
          placeholder="全部类别"
          clearable
          class="category-select"
          @change="filterByCategory"
        >
          <el-option label="全部" :value="null"></el-option>
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.categoryName"
            :value="category.id"
          />
        </el-select>
      </div>
      
      <el-button 
        type="primary" 
        icon="Plus" 
        class="add-button"
        @click="openAddDialog"
      >
        新增商品
      </el-button>
    </div>

    <!-- 商品列表表格 -->
    <el-card class="table-card">
      <el-table
        :data="paginatedGoods"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        row-key="id"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID"  align="center" />
        <el-table-column label="商品" width="220">
          <template #default="scope">
            <div class="goods-info-cell">
              <el-image
                v-if="scope.row.image"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                fit="cover"
                class="goods-image"
              />
              <div class="goods-text-info">
                <div class="goods-name">{{ scope.row.goodsName }}</div>
                <div class="goods-desc">{{ scope.row.goodsInfo || '暂无描述' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="类别" >
          <template #default="scope">
            <el-tag effect="plain" type="info">{{ scope.row.categoryName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="buyPrice" label="价格(元)"  align="center" />
        <el-table-column prop="goodsUnit" label="规格"  align="center" />
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="scope">
            <el-button 
              type="primary" 
              icon="Edit" 
              size="small" 
              circle
              @click="openEditDialog(scope.row)"
              class="action-btn"
            />
            <el-button 
              type="danger" 
              icon="Delete" 
              size="small" 
              circle
              @click="confirmDeleteGoods(scope.row.id)"
              class="action-btn"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredGoods.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>

    <!-- 新增/编辑商品弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogType === 'add' ? '新增商品' : '编辑商品'" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="currentGoods" 
        label-width="100px" 
        label-position="left"
        :rules="rules"
        ref="goodsForm"
      >
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="currentGoods.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        
        <el-form-item label="商品价格" prop="buyPrice">
          <el-input-number 
            v-model="currentGoods.buyPrice" 
            :min="0" 
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="商品类别" prop="categoryId">
          <el-select 
            v-model="currentGoods.categoryId" 
            placeholder="请选择商品类别"
            style="width: 100%"
            clearable
          >
            <el-option 
              v-for="category in categories" 
              :key="category.id" 
              :label="category.categoryName" 
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品规格" prop="goodsUnit">
          <el-input v-model="currentGoods.goodsUnit" placeholder="例如: 500ml/瓶" />
        </el-form-item>
        
        <el-form-item label="商品描述" prop="goodsInfo">
          <el-input 
            v-model="currentGoods.goodsInfo" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入商品描述信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="商品图片">
          <el-upload
            class="image-uploader"
            action="http://localhost:8080/upload"
            :show-file-list="false"
            :on-success="handleImageUploadSuccess"
            :before-upload="beforeImageUpload"
          >
            <el-image 
              v-if="currentGoods.image" 
              :src="currentGoods.image" 
              fit="cover" 
              class="uploaded-image"
            />
            <el-icon v-else class="uploader-icon">
              <Plus />
              <span class="upload-text">上传图片</span>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">
          {{ dialogType === 'add' ? '确认新增' : '确认修改' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import Header from '@/views/ui/header.vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { getGoodsListApi, addGoodsApi, getGoodsInfoByIdApi, updateGoodsInfoApi, deleteGoodsByIdApi } from '@/apis/GoodsManagerApi';
import { getCategoryListApi } from '@/apis/CategoryManagerApi';
import { Search, Plus } from '@element-plus/icons-vue';

// 数据状态
const goodsList = ref([]);
const searchKeyword = ref('');
const selectedCategory = ref(null);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogType = ref('add');
const categories = ref([]);

// 表单数据
const currentGoods = reactive({
  id: null,
  goodsName: '',
  buyPrice: 0,
  goodsInfo: '',
  image: '',
  goodsUnit: '',
  categoryId: null
});

// 表单验证规则
const rules = {
  goodsName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  buyPrice: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择商品类别', trigger: 'change' }],
  goodsUnit: [{ required: true, message: '请输入商品规格', trigger: 'blur' }]
};

// 计算属性
const filteredGoods = computed(() => {
  let result = goodsList.value;
  
  // 按搜索关键词过滤
  if (searchKeyword.value) {
    result = result.filter(goods =>
      goods.goodsName.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }
  
  // 按类别过滤
  if (selectedCategory.value!== null) {
    result = result.filter(goods => 
      goods.categoryId === selectedCategory.value
    );
  }
  
  return result;
});

const paginatedGoods = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredGoods.value.slice(start, end);
});

// 方法
const fetchGoodsList = async () => {
  try {
    loading.value = true;
    const res = await getGoodsListApi();
    goodsList.value = res.data;
  } catch (error) {
    console.error('获取商品列表失败:', error);
    ElMessage.error('获取商品列表失败');
  } finally {
    loading.value = false;
  }
};

const fetchCategoryList = async () => {
  try {
    const res = await getCategoryListApi();
    categories.value = res.data;
  } catch (error) {
    console.error('获取分类列表失败:', error);
    ElMessage.error('获取分类列表失败');
  }
};

const openAddDialog = () => {
  dialogType.value = 'add';
  Object.assign(currentGoods, {
    id: null,
    goodsName: '',
    buyPrice: 0,
    goodsInfo: '',
    image: '',
    goodsUnit: '',
    categoryId: null
  });
  dialogVisible.value = true;
};

const openEditDialog = async (goods) => {
  dialogType.value = 'edit';
  try {
    const res = await getGoodsInfoByIdApi(goods.id);
    Object.assign(currentGoods, res.data);
    dialogVisible.value = true;
  } catch (error) {
    console.error('获取商品详情失败:', error);
    ElMessage.error('获取商品详情失败');
  }
};

const submitForm = async () => {
  try {
    if (dialogType.value === 'add') {
      await addGoodsApi(currentGoods);
      ElMessage.success('新增商品成功');
    } else {
      await updateGoodsInfoApi(currentGoods);
      ElMessage.success('更新商品成功');
    }
    dialogVisible.value = false;
    fetchGoodsList();
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error(dialogType.value === 'add' ? '新增商品失败' : '更新商品失败');
  }
};

const confirmDeleteGoods = (id) => {
  ElMessageBox.confirm('确定要删除该商品吗？此操作不可撤销', '删除确认', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  }).then(async () => {
    try {
      await deleteGoodsByIdApi(id);
      ElMessage.success('删除商品成功');
      fetchGoodsList();
    } catch (error) {
      console.error('删除商品失败:', error);
      ElMessage.error('删除商品失败');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

const handleImageUploadSuccess = (response) => {
  if (response.code === 1) {
    currentGoods.image = response.data.url;
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error(response.message || '图片上传失败');
  }
};

const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件');
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB');
  }

  return isImage && isLt2M;
};

const handleSizeChange = (size) => {
  pageSize.value = size;
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
};

const searchGoods = () => {
  currentPage.value = 1;
};

const filterByCategory = () => {
  currentPage.value = 1;
};

// 生命周期
onMounted(() => {
  fetchGoodsList();
  fetchCategoryList();
});
</script>

<style scoped>
.goods-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 24px;
}

.action-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.filter-container {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  max-width: 600px;
}

.search-input {
  flex: 2;
  border-radius: 20px;
}

.category-select {
  flex: 1;
  min-width: 120px;
}

.add-button {
  border-radius: 20px;
  padding: 10px 20px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.goods-info-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.goods-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
}

.goods-text-info {
  display: flex;
  flex-direction: column;
}

.goods-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.goods-desc {
  font-size: 12px;
  color: #909399;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.action-btn {
  margin: 0 4px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

.image-uploader {
  width: 150px;
  height: 150px;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.image-uploader:hover {
  border-color: #409eff;
}

.uploaded-image {
  width: 100%;
  height: 100%;
}

.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-text {
  font-size: 12px;
  margin-top: 8px;
  color: #606266;
}
</style>    